﻿using CKS2320.Common;
using CKS2320.Common.Model;
using CKS2320.Common.Transfer;
using CKS2320.Common.Utils;
using CKS2320.Domain.DBEntity;
using CKS2320.Repository;
using CKS2320.Repository.Interface;
using CKS2320.Service.Interface;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CKS2320.Service
{
    public class ThicknessDetectionService : IThicknessDetectionService
    {
        public IThicknessDetectionRepository _thicknessDetectionRepository;
        public ThicknessDetectionService(IThicknessDetectionRepository thicknessDetectionRepository)
        {
            _thicknessDetectionRepository = thicknessDetectionRepository;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        public ResultReturn Add(ThicknessDetectionModel tdModel)
        {
            ParaShowSetModel para = ParaJsonLoad();
            float? FacadeCamber = null;
            float? TotalLength = null;
            float? backScallop2Pitch = null;
            float? backScallop2Diameter = null;
            float? backScallop3Pitch = null;
            float? backScallop3Diameter = null;
            float? frontScallop2Pitch = null;
            float? frontScallop2Diameter = null;
            float? frontScallop3Pitch = null;
            float? frontScallop3Diameter = null;
            float? maxThickness = null;
            float? MiniThickness = null;
            string? FinalJudge = null;
            float? maxThickness_Front = null;
            float? MinThickness_Front = null;
            float? maxThickness_Back = null;
            float? MinThickness_Back = null;
            float? SC01 = null;
            float? SC02 = null;
            float? SC03 = null;
            float? SC04 = null;
            bool result = false;
            string fs1 = "FS" + para.FS1;
            string fs2 = "FS" + para.FS2;
            string fd1 = "FD" + para.FD1;
            string fd2 = "FD" + para.FD2;
            string bs1 = "BS" + para.BS1;
            string bs2 = "BS" + para.BS2;
            string bd1 = "BD" + para.BD1;
            string bd2 = "BD" + para.BD2;
            string Atck = para.TKA;//A膜厚补偿
            string Btck = para.TKB;
            float Com = 0;
            Thicknessdetection TDEntity = new()
            {
                Id = Guid.NewGuid(),
                StationCode = tdModel.StationCode,
                Heart1 = tdModel.Heart1,
                StartUpLoad = tdModel.StartUpLoad,
                Heart2 = tdModel.Heart2,
                EndUpLoad = tdModel.EndUpLoad,
                PartCode = tdModel.PartCode,
                _3dscannerStart = tdModel._3dscannerStart,
                _3dscannerEnd = tdModel._3dscannerEnd,
                _3dscannerResult = tdModel._3dscannerResult1,
                TotalLengthResult = tdModel.TotalLengthResult,
                CrlargeEndDistanceResult = tdModel.CrlargeEndDistanceResult,
                CrsmallEndDistanceResult = tdModel.CrsmallEndDistanceResult,
                Crfront1WaveDistanceResult = tdModel.Crfront1WaveDistanceResult,
                Crfront64WaveDistanceResult = tdModel.Crfront64WaveDistanceResult,
                BackThicknessResult1 = tdModel.BackThicknessResult1,
                BackThicknessResult2 = tdModel.BackThicknessResult2,
                BackThicknessResult3 = tdModel.BackThicknessResult3,
                BackThicknessResult4 = tdModel.BackThicknessResult4,
                BackThicknessResult5 = tdModel.BackThicknessResult5,
                BackThicknessResult6 = tdModel.BackThicknessResult6,
                BackThicknessResult7 = tdModel.BackThicknessResult7,
                FrontThicknessResult1 = tdModel.FrontThicknessResult1,
                FrontThicknessResult2 = tdModel.FrontThicknessResult2,
                FrontThicknessResult3 = tdModel.FrontThicknessResult3,
                FrontThicknessResult4 = tdModel.FrontThicknessResult4,
                FrontThicknessResult5 = tdModel.FrontThicknessResult5,
                FrontThicknessResult6 = tdModel.FrontThicknessResult6,
                FrontThicknessResult7 = tdModel.FrontThicknessResult7,
                SmallEndDirectionInspectionResult = tdModel.SmallEndDirectionInspectionResult,
                FacadeCurvatureResult = tdModel.FacadeCurvatureResult,
                Result = tdModel.Result,
                RunType = tdModel.RunType,
                CreatedTime = DateTime.Now,
                ModifiedTime = DateTime.Now
            };
            List<Detectiondetail> detailList = new();
            if (tdModel.detaillist.Any())
            {
                foreach (var item in tdModel.detaillist)
                {
                    detailList.Add(new Detectiondetail()
                    {
                        Id = Guid.NewGuid(),
                        ParentId = TDEntity.Id,
                        DetectedType = item.DetectedType,
                        DetectedTypeDisplay = item.DetectedTypeDisplay,
                        DetectedData = item.DetectedData,
                        Description = item.Description,
                        DetectedIndex = item.DetectedIndex,
                        DetectedStatus = item.DetectedStatus,
                        DetectedTime = item.DetectedTime,
                        PartCode = item.PartCode,
                        Plcip = item.Plcip,
                        CreatedTime = DateTime.Now,
                        ModifiedTime = DateTime.Now
                    });
                }
                if (tdModel.RunType == "A")
                {
                    if (!string.IsNullOrEmpty(Atck))
                    {
                        Com = float.Parse(Atck);
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(Btck))
                    {
                        Com = float.Parse(Btck);
                    }
                }
                FacadeCamber = tdModel.detaillist.Where(p => p.DetectedType == "Cam").FirstOrDefault()?.DetectedData;
                backScallop2Pitch = tdModel.detaillist.Where(p => p.DetectedType == "BS3").FirstOrDefault()?.DetectedData;
                //backScallop2Diameter = tdModel.detaillist.Where(p => p.DetectedType == "BD3").FirstOrDefault()?.DetectedData;
                //backScallop3Pitch = tdModel.detaillist.Where(p => p.DetectedType == "BS3").FirstOrDefault()?.DetectedData;
                //backScallop3Diameter = tdModel.detaillist.Where(p => p.DetectedType == "BD3").FirstOrDefault()?.DetectedData;
                frontScallop2Pitch = tdModel.detaillist.Where(p => p.DetectedType == "FS3").FirstOrDefault()?.DetectedData;
                //frontScallop2Diameter = tdModel.detaillist.Where(p => p.DetectedType == "BD3").FirstOrDefault()?.DetectedData;
                //frontScallop3Pitch = tdModel.detaillist.Where(p => p.DetectedType == "BS3").FirstOrDefault()?.DetectedData;
                //frontScallop3Diameter = tdModel.detaillist.Where(p => p.DetectedType == "BD3").FirstOrDefault()?.DetectedData;
                //var FrontThickness = tdModel.detaillist.Where(p => p.DetectedTypeDisplay == "FCT" || p.DetectedTypeDisplay == "BCT").ToList();
                //if (FrontThickness != null && FrontThickness.Count > 0)
                //{
                //    maxThickness = FrontThickness.Max(p => p.DetectedData);
                //    MiniThickness = FrontThickness.Min(p => p.DetectedData);
                //}
                //SC01 = tdModel.detaillist.Where(p => p.DetectedType == "SC01").FirstOrDefault()?.DetectedData;
                //SC02 = tdModel.detaillist.Where(p => p.DetectedType == "SC02").FirstOrDefault()?.DetectedData;
                var FrontThickness_Front = tdModel.detaillist.Where(p => p.DetectedTypeDisplay == "FCT" && p.DetectedData != -100).ToList();
                if (FrontThickness_Front != null && FrontThickness_Front.Count > 0)
                {
                    maxThickness_Front = FrontThickness_Front.Max(p => p.DetectedData);
                    MinThickness_Front = FrontThickness_Front.Min(p => p.DetectedData);
                }
                var FrontThickness_Back = tdModel.detaillist.Where(p => p.DetectedTypeDisplay == "BCT" && p.DetectedData != -100).ToList();
                if (FrontThickness_Back != null && FrontThickness_Back.Count > 0)
                {
                    maxThickness_Back = FrontThickness_Back.Max(p => p.DetectedData);
                    MinThickness_Back = FrontThickness_Back.Min(p => p.DetectedData);
                }
                SC01 = tdModel.detaillist.Where(p => p.DetectedType == "SC01").FirstOrDefault()?.DetectedData;
                SC02 = tdModel.detaillist.Where(p => p.DetectedType == "SC02").FirstOrDefault()?.DetectedData;
                SC03 = tdModel.detaillist.Where(p => p.DetectedType == "SC03").FirstOrDefault()?.DetectedData;
                SC04 = tdModel.detaillist.Where(p => p.DetectedType == "SC04").FirstOrDefault()?.DetectedData;
            }
            if (tdModel.FacadeCurvatureResult == true)
            {
                FinalJudge = "OK";
            }
            else
            {
                FinalJudge = "NG";
            }
            if (tdModel.Crfront64WaveDistanceResult == true && tdModel.Crfront1WaveDistanceResult == true && tdModel.CrlargeEndDistanceResult == true && tdModel.CrsmallEndDistanceResult == true)
            {
                result = true;
            }
            Op30coredata op30CoreData = new Op30coredata()
            {
                SerialNumber = tdModel.PartCode,
                TestTime = DateTime.Now,
                Passageway = tdModel.RunType,
                FacadeCamber = FacadeCamber,
                CamberJudge = tdModel.FacadeCurvatureResult == true ? "OK" : "NG",
                BackScallop2Pitch = backScallop2Pitch,
                //BackScallop2Diameter = backScallop2Diameter,
                //BackScallop3Pitch = backScallop3Pitch,
                //BackScallop3Diameter = backScallop3Diameter,
                FrontScallop2Pitch = frontScallop2Pitch,
                //FrontScallop2Diameter = frontScallop2Diameter,
                //FrontScallop3Pitch = frontScallop3Pitch,
                //FrontScallop3Diameter = frontScallop3Diameter,
                MaxThickness = maxThickness_Front + Com,
                MaxThicknessJudge = tdModel.FrontThicknessResult2 == true ? "OK" : "NG",
                MiniThickness = MinThickness_Front + Com,
                MiniThicknessJudge = tdModel.FrontThicknessResult3 == true ? "OK" : "NG",
                FinalJudge = tdModel.Result == true ? "OK" : "NG",
                //sc01 = maxThickness_Back+Com,
                NonPositiveMaxThickness = maxThickness_Back + Com,
                // sc01judge= tdModel.Crfront64WaveDistanceResult == true ? "OK" : "NG",
                //sc02 = MinThickness_Back+Com,
                NonPositiveMiniThickness = MinThickness_Back + Com,
                // sc02judge = tdModel.Crfront1WaveDistanceResult == true ? "OK" : "NG",
                sc01 = SC01,
                sc02 = SC02,
                sc03 = SC03,
                sc03judge = tdModel.CrlargeEndDistanceResult == true ? "OK" : "NG",
                sc04 = SC04,
                sc04judge = tdModel.CrsmallEndDistanceResult == true ? "OK" : "NG",
                sedJudge = tdModel.SmallEndDirectionInspectionResult == true ? "OK" : "NG",
                scTotalJudge = result == true ? "OK" : "NG",
                ThicknessJudge = tdModel.FrontThicknessResult1 == true ? "OK" : "NG"
            };
            return _thicknessDetectionRepository.Add(TDEntity, detailList, op30CoreData);
        }
        public ParaShowSetModel ParaJsonLoad()
        {
            string filePath = "ParaSet.json";
            string text = File.ReadAllText(filePath);
            return JsonConvert.DeserializeObject<ParaShowSetModel>(text);
        }
        public ResultReturn AddPerformanceRecord(PerformanceRecord record)
        {
            return _thicknessDetectionRepository.AddPerformanceRecord(record);
        }
        /// <summary>
        /// 保存基恩士激光扫描仪
        /// </summary>
        /// <param name="tdModel"></param>
        /// <returns></returns>
        public ResultReturn KeyenceAdd(List<DetectionDetail> keyenceModel)
        {
            List<Detectiondetail> detailList = new();
            if (keyenceModel != null && keyenceModel.Any())
            {
                var detection = _thicknessDetectionRepository.GetByID(keyenceModel.First().ParentId);
                foreach (var item in keyenceModel)
                {
                    detailList.Add(new Detectiondetail()
                    {
                        Id = Guid.NewGuid(),
                        ParentId = item.ParentId.Value,
                        CreatedTime = DateTime.Now,
                        DetectedIndex = item.DetectedIndex,
                        DetectedStatus = item.DetectedStatus,
                        DetectedTime = item.DetectedTime,
                        DetectedType = item.DetectedType,
                        DetectedTypeDisplay = item.DetectedTypeDisplay,
                        ModifiedTime = DateTime.Now,
                        PartCode = detection?.PartCode ?? "",
                        Description = item.Description,
                        DetectedData = item.DetectedData,
                        Plcip = item.Plcip
                    });
                }
                return _thicknessDetectionRepository.KeyenceAdd(detailList);
            }
            return MessageInfoUtils.Success();
        }

        /// <summary>
        /// 导出3D线扫数据
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public ResultReturn Export3DKeyenceList(TotalReq req)
        {
            var query = _thicknessDetectionRepository.Export3DKeyenceList(req);
            List<ReturnKeyValueList> returnKeyValueLists = ModelUtils.ReturnTransfor(query);
            FileOperation fileOperation = new();
            return fileOperation.FileExport(returnKeyValueLists, "检测记录", "Export_" + DateTime.Now.ToString("yyyyMMddHHmms"));
        }
    }
}
